package controller

import (
	"vpn-server/middleware"
	"vpn-server/service"

	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	"github.com/kataras/jwt"
	"golang.org/x/crypto/bcrypt"
)

/**
 * 管理员控制器
 */
type AuthController struct {
	//iris框架自动为每个请求都绑定上下文对象
	Ctx iris.Context

	//admin功能实体
	Service service.AuthService
}

type AuthLogin struct {
	UserName string `json:"username"`
	Password string `json:"password"`
}

/**
 * 退出登录功能
 * 请求类型：Get
 * 请求url：admin/singout
 */
func (ac *AuthController) GetLogout() mvc.Result {
	err := ac.Ctx.Logout()
	if err != nil {
		return mvc.Response{
			Object: map[string]interface{}{
				"cdoe":    400,
				"message": "退出登录失败",
			},
		}
	} else {
		return mvc.Response{
			Object: map[string]interface{}{
				"cdoe":    0,
				"message": "退出登录成功",
			},
		}
	}

	// return mvc.Response{
	// 	Object: map[string]interface{}{
	// 		"status":  utils.RECODE_OK,
	// 		"success": utils.Recode2Text(utils.RESPMSG_SIGNOUT),
	// 	},
	// }
}

/**
 * 管理员登录功能
 * 接口：/admin/login
 */
func (ac *AuthController) PostLogin(context iris.Context) mvc.Result {

	iris.New().Logger().Info(" admin login ")

	var authLogin AuthLogin
	ac.Ctx.ReadJSON(&authLogin)

	//数据参数检验
	if authLogin.UserName == "" || authLogin.Password == "" {
		return mvc.Response{
			Object: map[string]interface{}{
				"code":    400,
				"success": "登录失败",
				"message": "用户名或密码为空,请重新填写后尝试登录",
			},
		}
	}

	//根据用户名、密码到数据库中查询对应的管理信息
	admin, exist := ac.Service.GetByAdminNameAndPassword(authLogin.UserName)

	//管理员不存在
	if !exist {
		return mvc.Response{
			Object: map[string]interface{}{
				"code":    400,
				"success": "登录失败",
				"message": "用户名错误,请重新登录",
			},
		}
	}

	//或者密码
	err := bcrypt.CompareHashAndPassword([]byte(admin.Pwd), []byte(authLogin.Password))

	if err != nil {
		return mvc.Response{
			Object: map[string]interface{}{
				"code":    400,
				"success": "登录失败",
				"message": "密码错误,请重新登录",
			},
		}
	} else {
		token, err := middleware.NewGetToken(authLogin.UserName)
		if err != nil {

			return mvc.Response{
				Object: map[string]interface{}{
					"code":    400,
					"success": "登录失败",
					"message": "token 生成失败",
				},
			}

		}

		return mvc.Response{
			Object: map[string]interface{}{
				"code":    0,
				"success": "登录成功",
				"message": "管理员登录成功",
				"token":   token,
			},
		}

	}

}

func (ac *AuthController) GetPwd(context iris.Context) mvc.Result {

	hash, err := bcrypt.GenerateFromPassword([]byte("123456"), bcrypt.DefaultCost)
	if err != nil {
		panic(err)
	}
	encodePWD := string(hash)

	return mvc.Response{
		Object: map[string]interface{}{
			"hash": encodePWD,
		},
	}
}

func (ac *AuthController) GetRefreshtoken(ctx iris.Context) mvc.Result {

	username := ctx.URLParam("username")

	refreshToken := []byte(ctx.URLParam("refresh_token"))
	if len(refreshToken) == 0 {
		// You can read the whole body with ctx.GetBody/ReadBody too.
		var tokenPair jwt.TokenPair
		if err := ctx.ReadJSON(&tokenPair); err != nil {
			ctx.StopWithError(iris.StatusBadRequest, err)
			return mvc.Response{
				Object: map[string]interface{}{
					"code": 400,
				},
			}
		}

		refreshToken = tokenPair.RefreshToken
	}

	_, err := middleware.NewVerifyToken(refreshToken, username)
	if err != nil {
		ctx.Application().Logger().Errorf("verify refresh token: %v", err)
		ctx.StatusCode(iris.StatusUnauthorized)
		return mvc.Response{
			Object: map[string]interface{}{
				"code": 400,
			},
		}
	}

	token, err := middleware.NewGetToken(username)

	if err != nil {

		return mvc.Response{
			Object: map[string]interface{}{
				"code":    400,
				"success": "登录失败",
				"message": "token 生成失败",
			},
		}

	}

	return mvc.Response{
		Object: map[string]interface{}{
			"code":    0,
			"success": "登录成功",
			"message": "管理员登录成功",
			"token":   token,
		},
	}
}
